package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee, Long[] ids) {

        //密码加密,使用用户名作为加密的“盐”
        employee.setPassword(new Md5Hash(employee.getPassword(), employee.getName()).toString());
        employeeMapper.insert(employee);

        /*if(ids!=null&&ids.length>0){
            for (Long rid : ids) {
                employeeMapper.saveRoleId(employee,rid);
            }
        }*/
        if (ids != null && ids.length > 0) {
            employeeMapper.saveRoleId(employee, ids);
        }
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);

        employeeMapper.deleteRoleRelation(employee.getId());
        if (ids != null && ids.length > 0) {
            employeeMapper.saveRoleId(employee, ids);
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRoleRelation(id);

        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> data = employeeMapper.queryForResult(qo);
        return new PageInfo<>(data);
    }

    @Override
    public Employee login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new RuntimeException("账号和密码不匹配");
        }
        return employee;
    }

    //更新密码
    @Override
    public void updatePwd(Employee employee, String oldPassword, String newPassword) {
        System.out.println(employee);
        String password = employee.getPassword();//已经加密
        String oldPasswordMd5 = new Md5Hash(oldPassword, employee.getName()).toString();//用户输入的密码
        if (password.equals(oldPasswordMd5)) {
            //如果和原密码相同,就执行
            //替换新密码
            //密码加密,使用用户名作为加密的“盐”
            employee.setPassword(new Md5Hash(newPassword, employee.getName()).toString());//把新的设置进去
            //employee.setPassword(newPassword);
            employeeMapper.updateByPrimaryKey2(employee);
        } else {
            throw new RuntimeException("密码和原密码不匹配");
        }
    }

    //重置密码
    @Override
    public void resetPwd(Employee employee, String newPassword) {
        //密码加密,使用用户名作为加密的“盐”
        employee.setPassword(new Md5Hash(newPassword, employee.getName()).toString());
        //employee.setPassword(newPassword);
        employeeMapper.updateByPrimaryKey2(employee);

    }

    @Override
    public void deleteBatch(Long[] ids) {
        employeeMapper.deleteBatch(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    /**
     * 导出
     * @return
     */
    @Override
    public Workbook exportXls() {
        //创建工作薄
        Workbook workbook = new HSSFWorkbook();
        //创建页面
        Sheet sheet = workbook.createSheet("员工通讯录");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        //从零开始查数据
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //从第一行开始放数据,索引从零开始
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        row.createCell(0).setCellValue("姓名");
        return workbook;
    }

    /**
     * 导入
     * @param file
     * @throws IOException
     */
    @Override
    public void importXls(MultipartFile file) throws IOException{
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读,从哪里读起就改成几
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            //判断如果用户名是空，就不再往下读
            if(!StringUtils.hasLength(name.trim())){
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());
            //获取文本格式的单元格内容
            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //获取数值类型的单元格内容
            //double value = row.getCell(2).getNumericCellValue();
            //employee.setAge((int)value);
            //设置默认密码1
            employee.setPassword("1");
            //调用保存方法
            this.save(employee,null);
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }
}
